package com.ourchem.bus.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.ourchem.bus.service.NacosDataTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author jh
 * @Description
 * @Date created in 17:06 2021/11/9
 */
@Service("nacosDataTokenService")
public class NacosDataTokenServiceImpl implements NacosDataTokenService {

    private final static Logger logger = LoggerFactory.getLogger(NacosDataTokenService.class);

    private final static String TOKEN_KEY = "bpm:datacenter:token";
    private final static int EXPIRE_HOURS = 2;

    /**
     * 配置文件在注册中心，新建或者直接赋值
     * */
    @Value("${datacenter.client.grant-type2:client_credentials}")
    String grantType;

    @Value("${datacenter.client.client-id2:}")
    String clientId;

    @Value("${datacenter.client.client-secret2:}")
    String clientSecret;

    @Value("${datacenter.token-url2:}")
    String tokenUrl;

    @Value("${datacenter.client.scope:select:}")
    String scope;

    @Value("${datacenter.client.userName:}")
    String userName;

    @Value("${datacenter.client.password:}")
    String password;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public String getToken() {
        Map<String, String> map = requestToken();
        return map.get("token");
    }

    @Override
    public String refreshToken() {
        delToken();
        return requestToken().get("token");
    }

    /**
     * 请求refresh_token
     */
    public String getRefreshToken(){
        Map<String, String> map = requestToken();
        return map.get("refreshToken");
    }
    /**
     * 请求token
     * @return
     */
    // @Cacheable(value = TOKEN_KEY, key = "access_token", secondaryCache = @SecondaryCache(expireTime = EXPIRE_HOURS, timeUnit = TimeUnit.HOURS))
    public Map<String,String> requestToken() {
        // Object tokenObj = redisTemplate.opsForValue().get(TOKEN_KEY);
        String token = "";
        String refreshToken="";
        Map<String,String> map = new HashMap();
        // if(Objects.isNull(tokenObj)) {
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", grantType);
        params.put("client_id", clientId);
        params.put("client_secret", clientSecret);
        params.put("refresh_token", "");
        params.put("username", userName);
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        params.put("password",pwd);
        HttpResponse response = HttpUtil.createGet(tokenUrl).form(params).execute();
        if(response.getStatus() == HttpStatus.HTTP_OK) {
            // logger.info("获取token成功！");
            // return JSON.parseObject(response.body()).getString("access_token");
            token = JSON.parseObject(response.body()).getString("access_token");
            refreshToken = JSON.parseObject(response.body()).getString("refresh_token");
            map.put("token",token);
            map.put("refreshToken",refreshToken);
            // redisTemplate.opsForValue().set(TOKEN_KEY, token, EXPIRE_HOURS, TimeUnit.HOURS);
        } else {
            throw new RuntimeException(String.format("获取数据中心token失败：%s", response.toString()));
        }
        // } else {
        //     token = (String) tokenObj;
        // }
        return map;
    }

    // @CacheEvict(value = TOKEN_KEY)
    public void delToken() {
        redisTemplate.delete(TOKEN_KEY);
    }



}
